<?php

$filename = "export_organisation_id_$organisation_id.csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv");

$row = array();
foreach ($report['ReportColumn'] as $column) {
    $row[] = '"' . $column['ReportColumnOption']['display_name'] . '"';
}

echo implode(",", $row) . "\r\n";

$count = 1;
foreach ($rows['Results'] as $row) {
    $row_arr = array();

    foreach ($report['ReportColumn'] as $column) {
        $field_name = $column['ReportColumnOption']['field_name'];
        $parts = explode(".", $field_name);
        $value = "";

        if (count($parts) > 1) {
            if (isset($row[$parts[0]][$parts[1]])) {
                $value = $row[$parts[0]][$parts[1]];
            } else if (isset($row[0][$parts[1]])) {
                $value = $row[0][$parts[1]];
            } else {
                $value = '';
            }
        }

        $row_arr[] = '"' . $value . '"';
    }

    echo implode(",", $row_arr) . "\r\n";
}
        